package com.example.springboottest.example.io.redirect.appserver.bio;

import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class BIOServer {
    public static void main(String[] args) {
        try {
            //创建ServerSocket监听8080
            ServerSocket server = new ServerSocket(8080);
            //等待客户端请求
            Socket socket = server.accept();
            //根据标准输入构造BufferedReader对象
            BufferedReader serverInput = new BufferedReader(new InputStreamReader(System.in));
            //通过Socket得到输入流，构造BufferedReader对象
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //通过Socket得到输出流，构造PrintWriter对象
            PrintWriter writer = new PrintWriter(socket.getOutputStream());
            //读取客户端请求
            System.out.println("客户端请求:\t" + reader.readLine());
            //读取输入信息
            String input = serverInput.readLine();
            while (!StringUtils.equals(input, "exit")) {
                writer.println(input);
                //向客户端输出该字符串
                writer.flush();
                //读取客户端请求
                System.out.println("客户端请求:" + reader.readLine());
                //读取下一条信息
                input = serverInput.readLine();
            }
            reader.close();
            writer.close();
            socket.close();
            server.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
